import { Component, HostBinding, Input, OnDestroy, Renderer2, ElementRef, ViewChild, Output, EventEmitter } from '@angular/core';
import { TabDirective } from './tab.directive';
import { TabsetConfig } from './tabset.config';

@Component({
    selector: 'tabset',
    templateUrl: './tabset.component.html',
    styleUrls: ['./tabset.component.css']
})
export class TabsetComponent implements OnDestroy {
    @HostBinding('class.gw-container-tabset') cls = true;

    @HostBinding('class.tab-container') clazz = true;

    @ViewChild('dhsvg') dhsvg: ElementRef;

    showAllNav = false;

    showAllNavBtn = false;

    @Input()
    get vertical(): boolean {
        return this._vertical;
    }

    set vertical(value: boolean) {
        this._vertical = value;
        this.setClassMap();
    }

    @Input()
    get justified(): boolean {
        return this._justified;
    }

    set justified(value: boolean) {
        this._justified = value;
        this.setClassMap();
    }

    @Input()
    get type(): string {
        return this._type;
    }

    set type(value: string) {
        this._type = value;
        this.setClassMap();
    }

    @Output()
        closeAllTabs: EventEmitter<any> = new EventEmitter();

    tabs: TabDirective[] = [];

    classMap: { [key: string]: boolean } = {};

    protected isDestroyed: boolean;

    private pageCanClosed = true;

    protected _vertical: boolean;

    protected _justified: boolean;

    protected _type: string;

    constructor(
        config: TabsetConfig,
        private renderer: Renderer2,
        private elementRef: ElementRef,
    ) {
        Object.assign(this, config);
        this.eventBingding();
    }

    ngOnDestroy(): void {
        this.isDestroyed = true;
    }

    /**
     * 添加标签页
     */
    addTab(tab: TabDirective): void {
        const index = this.tabs.findIndex((item) => item.id === 'default-hiden');
        if (index > 0) {
            this.tabs.splice(this.tabs.length - 1, 0, tab);
        } else {
            this.tabs.push(tab);
        }
        if (this.elementRef != null && this.elementRef.nativeElement !== null) {
            if (document.getElementById('iframetab').scrollWidth > window.innerWidth - 80) {
                this.showAllNavBtn = true;
            } else {
                this.showAllNavBtn = false;
                this.showAllNav = false;
            }
        }
    }

    /**
     * 点击切换
     */
    tabSwitch(tab: TabDirective) {}

    /**
     * 删除Tab
     */
    removeTab(tab: TabDirective, options = { reselect: true, emit: true }): void {
        const index = this.tabs.indexOf(tab);
        if (index === -1 || this.isDestroyed) {
            return;
        }
        if (options.reselect && tab.active && this.hasAvailableTabs(index)) {
            const newActiveIndex = this.getClosestTabIndex(index);
            this.tabs[newActiveIndex].active = true;
        }
        this.tabs.splice(index, 1);
        if (tab.elementRef.nativeElement.parentNode) {
            this.renderer.removeChild(tab.elementRef.nativeElement.parentNode, tab.elementRef.nativeElement);
        }
        if (options.emit) {
            tab.removed.emit(tab);
        }
        if (this.elementRef != null && this.elementRef.nativeElement !== null) {
            if (this.elementRef.nativeElement.querySelector('.nav').scrollWidth <= window.innerWidth - 80) {
                this.showAllNavBtn = false;
                this.showAllNav = false;
            } else {
                this.showAllNavBtn = true;
            }
        }
    }

    /**
     * 关闭Tab
     */
    closeApp(ev: Event, tab: TabDirective) {
        if (!this.pageCanClosed) {
            return;
        }
        ev && ev.stopPropagation();
        /**
         * appType为空，移除Tab
         */
        if (!tab.appType) {
            this.removeTab(tab);
            return;
        }

        const opts = {
            tabId: tab.id,
            appId: tab.appId,
            appEntrance: tab.appEntrance,
            funcId: tab.funcId,
            appType: tab.appType
        };
    }

    /**
     * 下拉按钮展示控制
     */
    showAllNavChange(ev: Event) {
        ev && ev.stopImmediatePropagation();
        this.showAllNav = !this.showAllNav;
    }

    closeAllAppTabs(ev: Event) {
        ev && ev.stopPropagation();
        this.closeAllTabs.emit('closeAllTabs');
    }

    /**
     * 获取兄弟Index
     */
    private getClosestTabIndex(index: number): number {
        const tabsLength = this.tabs.length;
        if (!tabsLength) {
            return -1;
        }

        for (let step = 1; step <= tabsLength; step += 1) {
            const prevIndex = index - step;
            const nextIndex = index + step;
            if (this.tabs[prevIndex] && !this.tabs[prevIndex].disabled && this.tabs[prevIndex].visible) {
                return prevIndex;
            }
            if (this.tabs[nextIndex] && !this.tabs[nextIndex].disabled && this.tabs[nextIndex].visible) {
                return nextIndex;
            }
        }

        return -1;
    }

    /**
     * 获取非禁用的Tabs
     */
    private hasAvailableTabs(index: number): boolean {
        const tabsLength = this.tabs.length;
        if (!tabsLength) {
            return false;
        }

        for (let i = 0; i < tabsLength; i += 1) {
            if (!this.tabs[i].disabled && i !== index) {
                return true;
            }
        }

        return false;
    }

    /**
     * 设置classMap
     */
    private setClassMap(): void {
        this.classMap = {
            'nav-stacked': this.vertical,
            'flex-column': this.vertical,
            'nav-justified': this.justified,
            [`nav-${this.type}`]: true
        };
    }

    public onchangeimg(obj) {
        obj.disabled = false;
    }

    public overchangeimg(obj) {
        obj.disabled = null;
    }

    public changekeyApplication(ev: Event, section, tabItem) {
        ev && ev.stopImmediatePropagation();
        // 导航滚动定位
        document.querySelector('#' + 'tabKey' + section).scrollIntoView();
        tabItem.active = true;
    }

    public closeAllnavPanel(ev: Event) {
        ev && ev.stopImmediatePropagation();
        this.showAllNav = false;
    }

    /**
     * 绑定事件
     */
    private eventBingding() {}
}
